package com.cswangdao.filter;


import com.cswangdao.threadlocal.BaseContext;
import com.cswangdao.utils.ResponseMineUtil;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

@WebFilter("/*")
public class AuthFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String uri = request.getRequestURI();
        if(uri.contains("/admin/auth/login")
                ||uri.contains("/admin/storage/create")
                ||uri.contains("/admin/storage/fetch")){
            filterChain.doFilter(request,response);
            return;
        }
        HttpSession session = request.getSession();
        Object adminId = session.getAttribute("adminId");
        if(Objects.isNull(adminId)){
            ResponseMineUtil.error(response,"请先登录");
            return;
        }
        BaseContext.setUserId(Integer.parseInt(adminId.toString()));
        filterChain.doFilter(request,response);
        BaseContext.remove();

    }
}
